package com.chen.jwt.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static final String APP_SECRET  = "ukc8BDbRigUDaY6pZFfWus2jZWLPHOsdadasdasfdssfeweee";
    /**
     * 生成token
     * @param map  传入payload
     * @return 返回token
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.MILLISECOND,20);
        instance.add(Calendar.DAY_OF_WEEK,7);
        // 创建 JWT builder
        JWTCreator.Builder builder = JWT.create();
        // payload
        map.forEach(builder::withClaim);
        // 设置过期时间
        builder.withExpiresAt(instance.getTime());
        // 设置签名加密  返回token
        return builder.sign(Algorithm.HMAC256(APP_SECRET));
    }
    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(APP_SECRET)).build().verify(token);
    }
    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(APP_SECRET)).build().verify(token);
    }
}